1
1
.
.
1
1
.
.
5
5
C
C
a
a
t
t
c
c
h
h
E
E
x
x
c
c
e
e
p
p
t
t
i
i
o
o
n
n
-
-
U
U
s
s
i
i
n
n
g
g
@
@
E
E
x
x
c
c
e
e
p
p
t
t
i
i
o
o
n
n
H
H
a
a
n
n
d
d
l
l
e
e
r
r
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to catch Validation Exceptions by adding @ExceptionHandler Methods to the Controller.
Such Methods can only catch Exceptions thrown inside the same Controller.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
hello()
MyController
http://localhost:8080/Hello
Browser
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_validation_catchexception_eceptionhandler (add Spring Boot Starters from the table)
Edit File: pom.xml (add validation dependency)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validat ion</artifactId>
</dependency>
MyController.java
package com.ivoronline.springboot_validation_catchexception_eceptionhandler.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Controller
@Validated
public class MyController {
//==================================================================
// HELLO
//==================================================================
@ResponseBody
@RequestMapping("/Hello")
public String hello(
@RequestParam @NotBlank String name,
@RequestParam @NotNull Integer age
) {
return "Hello " + name;
}
//==================================================================
// HANDLE EXCEPTIONS (it only catches first exception)
//==================================================================
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public String handleExceptions(MissingServletRequestParameterException exception) {
//GET EXCEPTION DETAILS
String parameterType = exception.getParameterType(); //String
String parameterName = exception.getParameterName(); //name
String message = exception.getMessage(); //Required String parameter 'name' is not present
//RETURN MESSAGE
return message;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello (reports only first error)
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>